package com.kd.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.kd.common.PageResult;
import com.kd.entity.Customer;
import lombok.Data;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;

public interface CustomerMapper extends BaseMapper<Customer> {



    @Select("<script>" +
            "SELECT " +
            "cid, " +  // 保持原名
            "company, " +
            "name, " +
            "active_count, " +  // 保持原名
            "cce, " +  // 保持原名
            "cpq " +   // 保持原名
            "FROM customer " +
            "<where>" +
            "  <if test='cursor != null'>" +
            "    <choose>" +
            "      <when test='isNext'>" +
            "        AND (cce * 10000) <![CDATA[<]]> #{cursor} " +
            "      </when>" +
            "      <otherwise>" +
            "        AND (cce * 10000) <![CDATA[>]]> #{cursor} " +
            "      </otherwise>" +
            "    </choose>" +
            "  </if>" +
            "</where>" +
            "ORDER BY cce DESC " +
            "LIMIT #{limit}" +
            "</script>")
    List<CustomerStats> selectCustomerStats(
            @Param("cursor") Long cursor,
            @Param("limit") Integer limit,
            @Param("isNext") Boolean isNext
    );

    @Update("UPDATE customer SET " +
            "active_count = active_count + #{countDelta}, " +
            "cce = cce + #{amountDelta}, " +
            "cpq = cpq + #{quantityDelta} " +
            "WHERE cid = #{cid}")
    int updateCustomerStats(
            @Param("cid") Integer cid,
            @Param("countDelta") int countDelta,
            @Param("amountDelta") BigDecimal amountDelta,
            @Param("quantityDelta") int quantityDelta
    );



    @Data
    public class CustomerStats {
        private Integer cid;          // 保持与数据库一致
        private String company;
        private String name;
        private Integer active_count; // 保持原名
        private BigDecimal cce;       // 保持原名
        private Integer cpq;          // 保持原名

        // 游标值计算方法（如果需要）
        @JsonIgnore
        public Long getCursorValue() {
            return cce.multiply(BigDecimal.valueOf(10000)).longValue();
        }
    }
}
